﻿using Autofac;
using EyFramework.Common.Entity;
using EyFramework.Common.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace EyFramework.Common
{
    /// <summary>
    /// 公共系统变量
    /// </summary>
    public static class Globals
    {
        #region AutoFac 的容器

        public static IContainer container = null;
        public static IList<string> assemblyList = new List<string>();

        #endregion AutoFac 的容器

        public static T GetService<T>()
        {
            return container.Resolve<T>();
        }

        #region 全局变量缓存

        /// <summary>
        /// 系统配置
        /// </summary>
        public static AppConfigure appConfigure = null;

        /// <summary>
        /// 启动参数封装成启动对象
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static StartUpArgs GetStartUpArgs(string[] args)
        {
            StartUpArgs startUpArgs = null;
            if (args.Length > 0)
            {
                startUpArgs = new StartUpArgs();
                foreach (var arg in args)
                {
                    var argSplit = arg.Split(new Char[] { '=' });
                    if (argSplit.Length > 1)
                    {
                        if (argSplit[0].Trim().ToUpper() == "LOGINNAME")
                        {
                            startUpArgs.LOGINNAME = argSplit[1].Trim();
                        }
                        else if (argSplit[0].Trim().ToUpper() == "PASSWORD")
                        {
                            startUpArgs.PASSWORD = argSplit[1].Trim();
                        }
                        else if (argSplit[0].Trim().ToUpper() == "SYSID")
                        {
                            startUpArgs.SYSID = argSplit[1].Trim();
                        }
                    }
                }
            }
            return startUpArgs;
        }

        public static void StartUpdate()
        {
            string updateExe = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "EyFramework.AutoUpdate.exe");
            string processNmae = Process.GetCurrentProcess().ProcessName;
            Process.Start(updateExe, string.Format("ProcessName={0} startCmd={1}", processNmae, Application.ExecutablePath));
            Application.Exit();
        }

        /// <summary>
        /// 判断当前程序是否需要更新
        /// </summary>
        /// <returns></returns>
        public static bool CheckUpdate()
        {
            IniFileUtil iniFile = new IniFileUtil(Path.Combine(DirectoryUtil.GetCurrentDirectory(), "AutoUpdate.ini"));
            string currentVersion = iniFile.IniReadValue("AutoUpdate", "AppVersion", "0.0.0");
            string updateUrl = iniFile.IniReadValue("AutoUpdate", "UpdateUrl");
            if (!string.IsNullOrEmpty(updateUrl))
            {
                VersionConfig versionConfig = GetCurrentVersion(updateUrl);
                if (IsNewVersion(versionConfig.Version, currentVersion))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 比较第一个版本是否比第二个版本新
        /// 如果是返回true 否则返回false
        /// </summary>
        /// <param name="version1">第一个版本</param>
        /// <param name="version2">第二个版本</param>
        /// <returns></returns>
        public static bool IsNewVersion(string pNewVersion, string pOldVersion)
        {
            SysVersion oldV = new SysVersion(pOldVersion);
            SysVersion newV = new SysVersion(pNewVersion);
            if (newV.MajorVersionNumber > oldV.MajorVersionNumber)
            {
                return true;
            }
            else if (newV.MajorVersionNumber == oldV.MajorVersionNumber)
            {
                if (newV.MinorVersionNumber > oldV.MinorVersionNumber)
                {
                    return true;
                }
                else if (newV.MinorVersionNumber == oldV.MinorVersionNumber)
                {
                    if (newV.BuildNumber > oldV.BuildNumber)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static VersionConfig GetCurrentVersion(string updateUrl)
        {
            string retString = string.Empty;
            //发起HTTP请求，获取当前服务器上的最新版本文件
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(updateUrl);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            VersionConfig uv = JsonConvert.DeserializeObject<VersionConfig>(retString);
            return uv;
        }

        /// <summary>
        /// 缓存登录用户信息
        /// </summary>
        public static LoginUser CurrentUser { get; set; }

        /// <summary>
        /// 异常日志处理器
        /// </summary>
        public static IExceptionHandler ExceptionHandler { set; get; }

        #endregion 全局变量缓存

        /// <summary>
        /// 保存异常日志
        /// </summary>
        /// <param name="ex"></param>
        public static void SaveException(Exception ex)
        {
            ExceptionHandler.SaveException(ex);
        }

        public static string GetBase64Str(string filePath)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取系统配置
        /// </summary>
        /// <param name="pKey"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static string GetSysConfig(string pKey, string defaultValue = "")
        {
            return appConfigure.GetSysConfig(pKey, defaultValue);
        }

        /// <summary>
        /// 返回配置项是true 和 false 类型的配置
        /// </summary>
        /// <param name="pKey"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static bool GetBoolSysConfig(string pKey, bool defaultValue = false)
        {
            return bool.Parse(appConfigure.GetSysConfig(pKey, defaultValue.ToString()));
        }

        /// <summary>
        /// 修改系统配置
        /// </summary>
        /// <param name="pKey">键</param>
        /// <param name="pValue">值</param>
        /// <param name="save">是否保存</param>
        public static void SetSysConfig(string pKey, string pValue, bool save = true)
        {
            appConfigure.SetSysConfig(pKey, pValue, save);
        }

        public static void StartCaculate()
        {
            #region [ 启动计算器 ]

            System.Diagnostics.Process proc;

            try
            {
                proc = new System.Diagnostics.Process
                {
                    StartInfo =
                    {
                        FileName = "calc.exe",
                        UseShellExecute = false,
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true
                    }
                };
                proc.Start();
            }
            catch (Exception ex)
            {
                proc = null;
                Globals.ShowError("计算器启动失败:" + ex.Message);
            }

            #endregion [ 启动计算器 ]
        }

        public static void StartNoteBook()
        {
            #region [ 启动记事本 ]

            System.Diagnostics.Process proc;

            try
            {
                // 启动记事本
                proc = new System.Diagnostics.Process
                {
                    StartInfo =
                    {
                        FileName = "notepad.exe",
                        UseShellExecute = false,
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true
                    }
                };
                proc.Start();
            }
            catch (Exception ex)
            {
                proc = null;
                Globals.ShowError("记事本启动失败:" + ex.Message);
            }

            #endregion [ 启动记事本 ]
        }

        #region 消息通知弹出实现

        /// <summary>
        /// 启动时需要初始化消息弹出实现
        /// </summary>
        public static IMsgUtil MsgUtil;

        public static void ShowTips(string pMsg)
        {
            MsgUtil.ShowTips(pMsg);
        }

        public static void ShowWarning(string pMsg)
        {
            MsgUtil.ShowWarning(pMsg);
        }

        public static void ShowError(string pMsg)
        {
            MsgUtil.ShowError(pMsg);
        }

        public static DialogResult ShowYesNoAndTips(string pMsg)
        {
            return MsgUtil.ShowYesNoAndTips(pMsg);
        }

        public static DialogResult ShowYesNoAndWarning(string pMsg)
        {
            return MsgUtil.ShowYesNoAndWarning(pMsg);
        }

        public static DialogResult ShowYesNoAndWarning(Form pForm, string pMsg)
        {
            return MsgUtil.ShowYesNoAndWarning(pForm, pMsg);
        }

        public static DialogResult ShowYesNoAndError(string pMsg)
        {
            return MsgUtil.ShowYesNoAndError(pMsg);
        }

        public static DialogResult ShowYesNoCancelAndTips(string pMsg)
        {
            return MsgUtil.ShowYesNoCancelAndTips(pMsg);
        }

        public static DialogResult ConfirmYesNo(string pMsg)
        {
            return MsgUtil.ConfirmYesNo(pMsg);
        }

        public static DialogResult ConfirmYesNoCancel(string pMsg)
        {
            return MsgUtil.ConfirmYesNoCancel(pMsg);
        }

        public static void ShowException(Exception ex)
        {
            MsgUtil.ShowException(ex);
        }

        public static void ShowInfoNotice(Form owner, string message, string caption = "")
        {
            MsgUtil.ShowInfoNotice(owner, message, caption);
        }

        public static void ShowWarningNotice(Form owner, string message, string caption = "")
        {
            MsgUtil.ShowWarningNotice(owner, message, caption);
        }

        public static void ShowErrorNotice(Form owner, string message, string caption = "")
        {
            MsgUtil.ShowErrorNotice(owner, message, caption);
        }

        #endregion 消息通知弹出实现

        /// <summary>
        /// 空值处理
        /// </summary>
        /// <param name="sValue"></param>
        /// <param name="defaltValue"></param>
        /// <returns></returns>
        public static string Nvl(string sValue, string defaltValue)
        {
            if (string.IsNullOrEmpty(sValue))
            {
                return defaltValue;
            }
            else
            {
                return sValue;
            }
        }

        /// <summary>
        /// 根据出生日期计算年龄岁数
        /// </summary>
        /// <param name="birthDay"></param>
        /// <param name="compDay"></param>
        /// <returns></returns>
        public static int GetAge(DateTime birthDay, DateTime compDay)
        {
            int age = compDay.Year - birthDay.Year;
            if (compDay.Month < birthDay.Month || (compDay.Month == birthDay.Month && compDay.Day < birthDay.Day))
            {
                age--;
            }
            return age < 0 ? 0 : age;
        }

        /// <summary>
        /// 根据出生日期计算年龄，并返回年龄
        /// 大于等于24个月的就按x岁计算
        /// 小于24个月，
        ///     大于等于2个月的，按X月结算
        ///     小于2个月的
        ///         大于等于2天的，按X天计算
        ///         小于2天的
        ///             大于等于2小时的，按X小时计算
        ///             小于2小时的，按X分钟计算
        /// </summary>
        /// <param name="birthDay"></param>
        /// <param name="compDay"></param>
        /// <returns></returns>
        public static SysAge GeSysAge(DateTime birthDay, DateTime compDay)
        {
            TimeSpan sp = compDay.Subtract(birthDay);
            int spDay = sp.Days;
            int spMonth = (compDay.Year - birthDay.Year) * 12 + (compDay.Month - birthDay.Month);

            if (spMonth >= 24)
            {
                return new SysAge(spMonth / 12, "岁");
            }
            else
            {
                if (spMonth >= 2)
                {
                    return new SysAge(spMonth, "月");
                }
                else
                {
                    if (sp.Days >= 2)
                    {
                        return new SysAge(sp.Days, "天");
                    }
                    else
                    {
                        int spHour = spDay * 24 + sp.Hours;//小时
                        if (spHour >= 2)
                        {
                            return new SysAge(spHour, "小时");
                        }
                        else
                        {
                            return new SysAge(sp.Minutes, "分钟");
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取菜单的快捷
        /// </summary>
        /// <param name="mENU_NAME"></param>
        /// <param name="hasCount"></param>
        /// <returns></returns>
        public static string MenuShortcut(string menuName, int hasCount)
        {
            if (!string.IsNullOrEmpty(menuName))
            {
                ;
                return menuName + "(&" + ((char)(65 + hasCount)).ToString().ToUpper() + ")";
            }
            return menuName;
        }

        public static string GetAgeAndUnit(DateTime birthDay, DateTime compDay)
        {
            return GeSysAge(birthDay, compDay).ToString();
        }

        /// <summary>
        /// 根据身份证号获取出生日期
        /// </summary>
        /// <param name="IdNo"></param>
        /// <returns></returns>
        public static String GetBirthByIdNo(string IdNo)
        {
            if (IdNo.Length == 18)
            {
                return IdNo.Substring(6, 4) + "-" + IdNo.Substring(10, 2) + "-" + IdNo.Substring(12, 2);
            }
            else if (IdNo.Length == 15)
            {
                return "19" + IdNo.Substring(6, 2) + "-" + IdNo.Substring(8, 2) + "-" + IdNo.Substring(10, 2);
            }
            else
            {
                return "";
            }
        }

        public static string GetSexByIdNo(string IdNo)
        {
            string sex = "";
            if (IdNo.Length == 18)
            {
                sex = IdNo.Substring(16, 1);
            }
            else if (IdNo.Length == 15)
            {
                sex = IdNo.Substring(14, 1);
            }
            else
            {
                return "";
            }
            //性别代码为偶数是女性奇数为男性
            if (int.Parse(sex) % 2 == 0)
            {
                return "女";
            }
            else
            {
                return "男";
            }
        }

        /// <summary>
        /// 文件转Base64字符串
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetFileBase64Str(string fileName)
        {
            FileStream fileStream = new FileStream(fileName, FileMode.Open);
            byte[] bt = new byte[fileStream.Length];
            fileStream.Read(bt, 0, bt.Length);
            fileStream.Close();
            return Convert.ToBase64String(bt);
        }
    }
}